#include "WifiTool.h"
#include "stdio.h"

uint8_t Wifi_receiveBuffer[1024];
fifo_struct Wifi_fifo;
volatile size_t WifiUartLineFlag = 0;
void WifiInit()
{
    uart_init(WIFI_UART, 2000000, WIFI_TX, WIFI_RX);
    uart_rx_interrupt(WIFI_UART, 1);
    fifo_init(&Wifi_fifo, FIFO_DATA_8BIT, Wifi_receiveBuffer, 1024);
}


size_t WifiPrintf(const char* fmt, ...)
{

    char buf[200] = { 0 };
    va_list arg;
    va_start(arg, fmt);
    size_t lenth = vsprintf(buf, fmt, arg);
    va_end(arg);
    uart_write_buffer(WIFI_UART, (uint8*) buf, lenth);
    return lenth;

}

void WifiUART_IRQHandler()
{
    char data = uart_read_byte(WIFI_UART);
    if (data == '\n')
        WifiUartLineFlag++;
    fifo_write_element(&Wifi_fifo, data);
}

size_t WifiReadBytes(uint8_t* buf, size_t len)
{
    size_t res = len;
    fifo_read_buffer(&Wifi_fifo, buf, &res, FIFO_READ_AND_CLEAN);
    return res;
}

int WifiReadLine(uint8_t* buf, size_t len)
{
    int lenth = 0;
    if (WifiUartLineFlag)
    {
        char data = 0;
        while (data != '\n' && lenth < len - 1)
        {
            fifo_read_element(&Wifi_fifo, &data, FIFO_READ_AND_CLEAN);
            buf[lenth] = data;
            lenth++;
        }
        lenth--;
        buf[lenth] = '\0';
        WifiUartLineFlag--;
    }
    return lenth;
}

#include <string.h>

int GetAudioRes()
{
    // "back", "carry", "front", "left", "leftturn", "null", "right", "rightturn", "stop"
    char* AudoLabel[9] = { "back","carry", "front", "left", "leftturn", "null", "right", "rightturn", "stop" };
    char AudioBufferp[256] = { 0 };

    // WifiPrintf("%d\n", WifiUartLineFlag);
    // WifiPrintf(AudioBufferp);
    if (WifiReadLine(AudioBufferp, 256))
    {
        // WifiPrintf(AudioBufferp);
        for (int i = 0; i < 9;i++)
        {
            if (strcmp(AudoLabel[i], AudioBufferp) == 0)
            {
                return i;
            }
        }
    }
    return 9;
}